const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa-cors');
const serve = require('koa-static');
const logger = require('koa-logger');
const path = require('path');

// 初始化应用
const app = new Koa();
const router = new Router();

// 中间件
app.use(logger());
app.use(cors({
  origin: '*',
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  headers: ['Content-Type', 'Authorization', 'Accept']
}));
app.use(bodyParser());
app.use(serve(path.join(__dirname, '../public')));

// 错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = {
      success: false,
      error: err.message || '内部服务器错误'
    };
    console.error('请求处理错误:', err);
  }
});

// 模拟数据
const mockData = {
  summary: {
    totalTokens: 150,
    totalSmartWallets: 25,
    generatedAt: new Date().toISOString(),
    topTokens: [
      { symbol: 'BTC', name: 'Bitcoin', score: 95.5 },
      { symbol: 'ETH', name: 'Ethereum', score: 92.3 },
      { symbol: 'SOL', name: 'Solana', score: 88.7 },
      { symbol: 'ADA', name: 'Cardano', score: 85.2 },
      { symbol: 'DOT', name: 'Polkadot', score: 82.9 }
    ],
    topSmartWallets: [
      { address: '0x1234567890abcdef1234567890abcdef12345678', score: 98.5 },
      { address: '0xabcdef1234567890abcdef1234567890abcdef12', score: 96.2 },
      { address: '0x567890abcdef1234567890abcdef1234567890ab', score: 94.8 },
      { address: '0xcdef1234567890abcdef1234567890abcdef1234', score: 92.1 },
      { address: '0x90abcdef1234567890abcdef1234567890abcdef', score: 89.7 }
    ]
  },
  tokens: [
    {
      symbol: 'BTC',
      name: 'Bitcoin',
      avgPrice: 45000.50,
      avgPriceChange24h: 2.5,
      avgVolume24h: 25000000000,
      avgMarketCap: 850000000000,
      sourceCount: 7,
      score: 95.5,
      category: 'large_cap',
      riskFactors: []
    },
    {
      symbol: 'ETH',
      name: 'Ethereum',
      avgPrice: 3200.75,
      avgPriceChange24h: 1.8,
      avgVolume24h: 15000000000,
      avgMarketCap: 380000000000,
      sourceCount: 7,
      score: 92.3,
      category: 'large_cap',
      riskFactors: []
    },
    {
      symbol: 'SOL',
      name: 'Solana',
      avgPrice: 120.25,
      avgPriceChange24h: -0.5,
      avgVolume24h: 2500000000,
      avgMarketCap: 45000000000,
      sourceCount: 6,
      score: 88.7,
      category: 'mid_cap',
      riskFactors: ['high_volatility']
    },
    {
      symbol: 'ADA',
      name: 'Cardano',
      avgPrice: 0.85,
      avgPriceChange24h: 3.2,
      avgVolume24h: 800000000,
      avgMarketCap: 28000000000,
      sourceCount: 5,
      score: 85.2,
      category: 'mid_cap',
      riskFactors: []
    },
    {
      symbol: 'DOT',
      name: 'Polkadot',
      avgPrice: 8.50,
      avgPriceChange24h: -1.2,
      avgVolume24h: 450000000,
      avgMarketCap: 12000000000,
      sourceCount: 5,
      score: 82.9,
      category: 'mid_cap',
      riskFactors: ['regulatory_risk']
    }
  ],
  smartMoney: [
    {
      address: '0x1234567890abcdef1234567890abcdef12345678',
      nickname: 'Whale Master',
      avgPnl7d: 125000,
      avgPnl30d: 580000,
      smartScore: 98.5,
      riskLevel: 'low',
      tags: ['whale', 'smart_money'],
      metrics: {
        winRate: 0.85,
        totalTrades: 245,
        avgHoldTime: 12.5,
        totalVolume: 15000000
      }
    },
    {
      address: '0xabcdef1234567890abcdef1234567890abcdef12',
      nickname: 'DeFi King',
      avgPnl7d: 95000,
      avgPnl30d: 420000,
      smartScore: 96.2,
      riskLevel: 'low',
      tags: ['defi', 'smart_money'],
      metrics: {
        winRate: 0.82,
        totalTrades: 189,
        avgHoldTime: 8.3,
        totalVolume: 12000000
      }
    },
    {
      address: '0x567890abcdef1234567890abcdef1234567890ab',
      nickname: 'Alpha Hunter',
      avgPnl7d: 78000,
      avgPnl30d: 350000,
      smartScore: 94.8,
      riskLevel: 'medium',
      tags: ['alpha', 'smart_money'],
      metrics: {
        winRate: 0.79,
        totalTrades: 156,
        avgHoldTime: 6.7,
        totalVolume: 8500000
      }
    }
  ],
  marketData: {
    overview: {
      totalMarketCap: { usd: 2500000000000 },
      totalVolume: { usd: 85000000000 },
      marketCapChange24h: 1.5,
      activeCryptocurrencies: 12500,
      markets: 850
    }
  },
  trends: {
    price: {
      direction: 'up',
      strength: 'medium',
      change: 0.025
    },
    volume: {
      direction: 'up',
      strength: 'high',
      change: 0.15
    }
  },
  risks: [
    {
      type: 'market_volatility',
      severity: 'medium',
      token: 'SOL',
      description: 'Solana显示出高波动性，可能存在短期价格风险'
    },
    {
      type: 'regulatory_risk',
      severity: 'low',
      token: 'DOT',
      description: 'Polkadot面临潜在的监管不确定性'
    },
    {
      type: 'liquidity_risk',
      severity: 'high',
      token: 'MEME',
      description: '某些meme币存在流动性不足的风险'
    }
  ]
};

// API路由
router.get('/api/health', async (ctx) => {
  ctx.body = {
    status: 'ok',
    timestamp: new Date().toISOString(),
    version: '1.0.0-test'
  };
});

router.get('/api/summary', async (ctx) => {
  ctx.body = {
    success: true,
    data: {
      summary: mockData.summary,
      metadata: {
        version: '1.0.0',
        generatedAt: new Date().toISOString(),
        dataCount: mockData.tokens.length,
        source: 'crypto-aggregator-test'
      },
      lastUpdate: new Date().toISOString()
    }
  };
});

router.get('/api/stats', async (ctx) => {
  ctx.body = {
    success: true,
    data: {
      tokens: {
        total: mockData.tokens.length,
        byCategory: {
          large_cap: 2,
          mid_cap: 3,
          small_cap: 0,
          micro_cap: 0
        },
        avgScore: 88.9,
        topScoring: mockData.tokens.slice(0, 5).map(t => ({
          symbol: t.symbol,
          score: t.score
        }))
      },
      smartMoney: {
        total: mockData.smartMoney.length,
        byRiskLevel: {
          low: 2,
          medium: 1,
          high: 0,
          very_high: 0
        },
        avgScore: 96.5,
        topPerforming: mockData.smartMoney.slice(0, 3).map(w => ({
          address: w.address.substring(0, 8) + '...',
          score: w.smartScore
        }))
      },
      risks: {
        total: mockData.risks.length,
        bySeverity: {
          low: 1,
          medium: 1,
          high: 1,
          critical: 0
        },
        byType: {
          market_volatility: 1,
          regulatory_risk: 1,
          liquidity_risk: 1
        }
      },
      lastUpdate: new Date().toISOString(),
      dataAge: 0
    }
  };
});

router.get('/api/tokens', async (ctx) => {
  const { 
    symbol, 
    category, 
    minScore = 0, 
    maxScore = 100,
    sortBy = 'score',
    order = 'desc',
    limit = 50, 
    offset = 0 
  } = ctx.query;

  let tokens = [...mockData.tokens];

  // 应用过滤器
  if (symbol) {
    tokens = tokens.filter(token => 
      token.symbol.toLowerCase().includes(symbol.toLowerCase())
    );
  }

  if (category) {
    tokens = tokens.filter(token => token.category === category);
  }

  tokens = tokens.filter(token => {
    const score = token.score || 0;
    return score >= parseFloat(minScore) && score <= parseFloat(maxScore);
  });

  // 排序
  tokens.sort((a, b) => {
    const aVal = a[sortBy] || 0;
    const bVal = b[sortBy] || 0;
    
    if (order === 'desc') {
      return bVal - aVal;
    } else {
      return aVal - bVal;
    }
  });

  // 分页
  const total = tokens.length;
  const paginatedTokens = tokens.slice(
    parseInt(offset), 
    parseInt(offset) + parseInt(limit)
  );

  ctx.body = {
    success: true,
    data: {
      tokens: paginatedTokens,
      pagination: {
        total,
        limit: parseInt(limit),
        offset: parseInt(offset),
        hasMore: parseInt(offset) + parseInt(limit) < total
      }
    }
  };
});

router.get('/api/tokens/:symbol', async (ctx) => {
  const { symbol } = ctx.params;
  
  const token = mockData.tokens.find(t => 
    t.symbol.toLowerCase() === symbol.toLowerCase()
  );

  if (!token) {
    ctx.status = 404;
    ctx.body = {
      success: false,
      error: `代币 ${symbol} 未找到`
    };
    return;
  }

  ctx.body = {
    success: true,
    data: token
  };
});

router.get('/api/smart-money', async (ctx) => {
  const { 
    minScore = 0,
    maxScore = 100,
    riskLevel,
    tags,
    sortBy = 'smartScore',
    order = 'desc',
    limit = 20, 
    offset = 0 
  } = ctx.query;

  let smartMoney = [...mockData.smartMoney];

  // 应用过滤器
  smartMoney = smartMoney.filter(wallet => {
    const score = wallet.smartScore || 0;
    return score >= parseFloat(minScore) && score <= parseFloat(maxScore);
  });

  if (riskLevel) {
    smartMoney = smartMoney.filter(wallet => wallet.riskLevel === riskLevel);
  }

  if (tags) {
    const tagList = tags.split(',').map(tag => tag.trim());
    smartMoney = smartMoney.filter(wallet => 
      tagList.some(tag => wallet.tags.includes(tag))
    );
  }

  // 排序
  smartMoney.sort((a, b) => {
    const aVal = a[sortBy] || 0;
    const bVal = b[sortBy] || 0;
    
    if (order === 'desc') {
      return bVal - aVal;
    } else {
      return aVal - bVal;
    }
  });

  // 分页
  const total = smartMoney.length;
  const paginatedData = smartMoney.slice(
    parseInt(offset), 
    parseInt(offset) + parseInt(limit)
  );

  ctx.body = {
    success: true,
    data: {
      smartMoney: paginatedData,
      pagination: {
        total,
        limit: parseInt(limit),
        offset: parseInt(offset),
        hasMore: parseInt(offset) + parseInt(limit) < total
      }
    }
  };
});

router.get('/api/smart-money/:address', async (ctx) => {
  const { address } = ctx.params;
  
  const wallet = mockData.smartMoney.find(w => w.address === address);

  if (!wallet) {
    ctx.status = 404;
    ctx.body = {
      success: false,
      error: `钱包 ${address} 未找到`
    };
    return;
  }

  ctx.body = {
    success: true,
    data: wallet
  };
});

router.get('/api/market-data', async (ctx) => {
  ctx.body = {
    success: true,
    data: mockData.marketData
  };
});

router.get('/api/trends', async (ctx) => {
  ctx.body = {
    success: true,
    data: mockData.trends
  };
});

router.get('/api/risks', async (ctx) => {
  const { severity, type } = ctx.query;
  
  let risks = [...mockData.risks];

  // 应用过滤器
  if (severity) {
    risks = risks.filter(risk => risk.severity === severity);
  }

  if (type) {
    risks = risks.filter(risk => risk.type === type);
  }

  ctx.body = {
    success: true,
    data: {
      risks,
      summary: {
        total: risks.length,
        bySeverity: risks.reduce((acc, risk) => {
          acc[risk.severity] = (acc[risk.severity] || 0) + 1;
          return acc;
        }, {}),
        byType: risks.reduce((acc, risk) => {
          acc[risk.type] = (acc[risk.type] || 0) + 1;
          return acc;
        }, {})
      }
    }
  };
});

router.get('/api/search', async (ctx) => {
  const { q, type = 'all', limit = 20 } = ctx.query;
  
  if (!q || q.trim().length < 2) {
    ctx.status = 400;
    ctx.body = {
      success: false,
      error: '搜索关键词至少需要2个字符'
    };
    return;
  }

  const results = {
    tokens: [],
    smartMoney: [],
    total: 0
  };

  const keyword = q.toLowerCase();

  // 搜索代币
  if (type === 'all' || type === 'tokens') {
    results.tokens = mockData.tokens.filter(token => 
      token.symbol.toLowerCase().includes(keyword) ||
      token.name.toLowerCase().includes(keyword)
    ).slice(0, parseInt(limit));
  }

  // 搜索聪明钱
  if (type === 'all' || type === 'smartMoney') {
    results.smartMoney = mockData.smartMoney.filter(wallet => 
      wallet.address.toLowerCase().includes(keyword) ||
      (wallet.nickname && wallet.nickname.toLowerCase().includes(keyword)) ||
      wallet.tags.some(tag => tag.toLowerCase().includes(keyword))
    ).slice(0, parseInt(limit));
  }

  results.total = results.tokens.length + results.smartMoney.length;

  ctx.body = {
    success: true,
    data: results,
    query: {
      keyword: q,
      type,
      limit: parseInt(limit)
    }
  };
});

router.post('/api/refresh', async (ctx) => {
  ctx.body = {
    success: true,
    message: '数据刷新已启动（测试模式）',
    data: {
      timestamp: new Date().toISOString()
    }
  };
});

// 主页路由
router.get('/', async (ctx) => {
  ctx.redirect('/index.html');
});

// API文档路由
router.get('/api', async (ctx) => {
  ctx.body = {
    name: 'Crypto Aggregator API (Test Mode)',
    version: '1.0.0-test',
    description: '加密货币信息聚合和分析系统API - 测试模式',
    note: '当前运行在测试模式，使用模拟数据'
  };
});

// 使用路由
app.use(router.routes());
app.use(router.allowedMethods());

// 错误处理
app.on('error', (err, ctx) => {
  console.error('应用错误:', err);
});

// 启动服务器
const port = 3000;
const host = '0.0.0.0';

app.listen(port, host, () => {
  console.log(`🚀 测试服务器运行在 http://${host}:${port}`);
  console.log(`📊 API文档: http://${host}:${port}/api`);
  console.log(`🌐 Web界面: http://${host}:${port}`);
  console.log(`⚠️  当前运行在测试模式，使用模拟数据`);
});

module.exports = app;

